<template>
  <div>
    <el-form :model="form" inline>
      <el-form-item label="用户名称"
        ><el-input v-model="form.name" placeholder="请输入用户名称"></el-input
      ></el-form-item>
      <el-form-item label="用户工号"
        ><el-input-number
          v-model="form.account"
          placeholder="请输入用户工号"
        ></el-input-number
      ></el-form-item>
      <el-button type="primary" @click="search">查 询</el-button>
    </el-form>
    <el-table :data="tableData">
      <el-table-column label="工号" prop="empno"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="用户类型" prop="status">
        <template slot-scope="scope">
          <span v-for="item in type" :key="item.id">
            <span v-if="scope.row.status === item.value">
              {{ item.name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createdTime"></el-table-column>
      <el-table-column label="更新时间" prop="updatedTime"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="reset(scope.row)" size="mini" type="text"
            >重置密码</el-button
          >
          <el-button @click="deleteHandler(scope.row)" size="mini" type="text"
            >删除</el-button
          >
          <el-button @click="changeAuthority(scope.row)" size="mini" type="text"
            >更改权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    ></el-pagination>
    <el-dialog title="重置密码" :visible.sync="dialogFormVisible">
      <el-form :model="formRule" :rules="formRules" ref="formRule" inline>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formRule.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-button type="primary" @click="submit('formRule')">确 认</el-button>
        <el-button @click="resetForm('formRule')">重置</el-button>
      </el-form>
    </el-dialog>
    <el-dialog title="更改用户类型" :visible.sync="showAuthority">
      <el-form inline v-model="userForm">
        <el-form-item label="用户类型">
          <el-select v-model="userForm.status">
            <el-option
              v-for="item in type"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="updateStatus">提 交</el-button>
    </el-dialog>
  </div>
</template>
  
  <script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { list, getTotal, detele, resetPassword } from "@/api/user";
import userType from "@/api/userType";
import { update } from "@/api/user";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("密码必须填写！"));
      } else if (value.length < 6) {
        callback(new Error("密码位数不得小于6！"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      type: [],
      showAuthority: false,
      formRule: { password: "" },
      form: { name: "", account: "" },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      formRules: {
        password: {
          required: true,
          validator: validatePassword,
          trigger: "blur",
        },
      },
      userForm: { status: "", id: 0 }, //user表
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    //更新用户类型
    updateStatus() {
      update(this.userForm)
        .then((res) => {
          this.$message({
            message: `${res.message}`,
            type: "success",
          });
          this.showAuthority = false;
          this.list(this.currentPage);
          this.getTotal();
        })
        .catch((err) => {
          this.$message({
            message: `${res.message}`,
            type: "error",
          });
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          resetPassword(this.userForm.id, this.formRule.password).then(
            (res) => {
              this.$message({
                message: `${res.message}`,
                type: "success",
              });
              this.dialogFormVisible = false;
              this.formRule = { password: "" };
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    changeAuthority(data) {
      this.userForm.id = data.id;
      this.userForm.status = data.status;
      this.showAuthority = true;
    },
    deleteHandler(data) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          detele(data.id).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.list(1);
            this.getTotal();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    reset(data) {
      this.formRule = { password: "" };
      this.userForm.id = data.id;
      this.dialogFormVisible = true;
    },
    search() {
      this.list(1);
      this.getTotal();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.list(currentPage);
    },
    list: async function (currentPage) {
      const res = await list(
        this.form.name,
        this.form.account,
        currentPage,
        this.pageSize
      );
      this.tableData = res.data;
    },
    getTotal: async function () {
      const res = await getTotal(this.form.name, this.form.account);
      this.total = res.data;
    },
    getUserType() {
      userType.getAll().then((res) => {
        this.type = res.data;
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getUserType();
    this.list(1);
    this.getTotal();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
  <style scoped>
</style>